package google.sites.model.commands.attachments;

import com.google.gdata.data.sites.AttachmentEntry;
import com.google.gdata.data.sites.ContentFeed;
import com.google.gdata.util.ServiceException;
import dev.tools.design.patterns.command.CommandException;
import google.sites.model.commands.SitesCommand;

import java.io.IOException;
import java.net.URL;

/**
 * Created with IntelliJ IDEA.
 * User: Nuno
 * Date: 04-10-2013
 * Time: 15:52
 */
public class DownloadAllAttachments extends SitesCommand {
    private String directory;

    @Override
    protected void protectedExecute() throws CommandException {
        try {
            URL contentFeedUrl = new URL(getContentFeedUrl() + "?kind=attachment");
            ContentFeed contentFeed = getService().getFeed(contentFeedUrl, ContentFeed.class);
            for (AttachmentEntry entry : contentFeed.getEntries(AttachmentEntry.class)) {
                new DownloadAttachment()
                        .setAttachmentEntry(entry)
                        .setDirectory(directory)
                        .execute();
            }
        } catch (ServiceException | IOException e) {
            throw new CommandException(e);
        }

    }

    public DownloadAllAttachments setDirectory(String directory) {
        this.directory = directory;
        return this;
    }
}
